package com.bitcs.accesscontrol.service;

import com.bitcs.accesscontrol.bean.ResponseVO;
import com.bitcs.accesscontrol.util.ErrorCode;
import com.bitcs.accesscontrol.util.Md5Util;
import com.bitcs.accesscontrol.util.ResponseUtil;
import com.bitcs.accesscontrol.util.RestConfig;
import org.springframework.stereotype.Service;

/**
 * @author GeChen
 */
@Service
public class TestService {
    /**
     * sign为输入的认证码，用于校验
     *
     * @param appId
     * @param sign
     * @return
     */
    public String test(String appId, String sign) {
        String salt = Md5Util.salt;
        /**
         * 通过appId和salt计算一个认证码
         */
        String calSign = Md5Util.md5(appId + salt);
        StringBuilder stringBuilder = new StringBuilder(RestConfig.UrlConst.baseUrl);
        stringBuilder.append("?");
        stringBuilder.append("appId=" + appId);
        stringBuilder.append("&");
        stringBuilder.append("type=" + RestConfig.UrlConst.baseType);
        String finalUrl = stringBuilder.toString();
        ResponseVO responseVO = RestConfig.restTemplate().getForObject(finalUrl, ResponseVO.class);
        if (responseVO.getCode() == 400) {
            return ResponseUtil.getResponseString(ErrorCode.APPID_NOT_EXIST, responseVO.getMessage(), "");
        }
        if (responseVO.getCode() == 401) {
            return ResponseUtil.getResponseString(ErrorCode.SERVICE_NOT_AVAILABLE, responseVO.getMessage(), "");
        }
        if (!sign.equals(calSign)) {
            return ResponseUtil.getResponseString(ErrorCode.SIGN_ERROR, "认证错误，请仔细校对认证码", "");
        } else {
            return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "", "");
        }
    }
}
